package main

import "net"
import (
	"fmt"
	"bufio"
	"rpc/client"
	"net/rpc"
	"time"

)
import (
	_ "net/http/pprof"
	"net/http"
)

/*
 	TO DO : replace fmt.Println with log
 	when serve down, no the fucking log
*/

func tcpCacheBufHander(conn *net.TCPConn)  {
	reader := bufio.NewReader(conn)
	writer := bufio.NewWriter(conn)
	var channel *Channel
	for{
		if err := conn.SetReadDeadline(time.Now().Add(time.Second*60*2)); err != nil {
			fmt.Println("SetReadDeadline error")
			break
		}
		p := &Proto{}
		if _,err := p.ReadTcp(reader);err != nil{
			fmt.Println("ReadTcp fail =>",err)
			break
		}
		if c,err := ProcessCmd(p,writer,conn);err != nil{
			break
		}else{
			if c != nil && p.Cmd == AUTH{
				channel = c
			}
		}
	}
	if channel != nil{
		RemoveChannel(channel)
	}else{
		if conn != nil{
			conn.Close()
		}
	}
	return
}

func handleAccept(tcpListener *net.TCPListener){
	for{

		conn,cerr := tcpListener.AcceptTCP()

		if cerr != nil{
			fmt.Println("Accept fail =>",cerr)
		}
		//fmt.Println("Accept one Connect :",conn.RemoteAddr())
		go tcpCacheBufHander(conn)
	}
}

var c *rpc.Client

func main() {
	// pprof
	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()

	c = client.InitRPC()
	InitChannelMap()
	InitUserRouter()
	go InitHttpSever()

	serverStr := "192.168.1.105:8133"
	tcpAddr,err := net.ResolveTCPAddr("tcp4",serverStr)
	if err != nil{
		fmt.Println("ResolveTCPAddr fail =>",err)
		return
	}

	tcpListener,terr := net.ListenTCP("tcp",tcpAddr)
	if terr != nil{
		fmt.Println("ListenerTCP fail =>",terr)
		return
	}


	fmt.Println("Listening ",serverStr," Begin")

	defer func() {
		if err := tcpListener.Close(); err != nil {
			fmt.Println("listener.Close() error(%v)", err)
		}
	}()

	for i:= 0;i < 10;i++{
		go handleAccept(tcpListener)
	}

	InitSignal()
}

